package com.bbs.common.realm;

import com.bbs.UserRoleInfo;
import com.bbs.model.UserParams;
import com.bbs.user.UserInfo;
import com.bbs.user.UserService_v2;
import com.bbs.utils.Common;
import lombok.extern.log4j.Log4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService_v2 userService;

    /**
     * 为当前subject授权（获取登录用户权限）
     * @param principalCollection
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userCode = (String)principalCollection.getPrimaryPrincipal();
        List<UserRoleInfo> userRoleInfos = userService.getUserRoleInfos(userCode);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(!userRoleInfos.isEmpty()) {
            for(UserRoleInfo role : userRoleInfos) {
                info.addRole(role.getROLE_CODE());
            }
        }
        return info;
    }

    /**
     * 认证登陆subject身份
     * @param authenticationToken
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserParams userParams = new UserParams();
        userParams.setUsername(token.getUsername());
        userParams.setPassword(Common.EncoderByMd5(String.valueOf(token.getPassword())));
        UserInfo userInfo = new UserInfo();
        userInfo.setUSER_NAME(token.getUsername());
        userInfo.setUSER_PWD(Common.EncoderByMd5(String.valueOf(token.getPassword())));

        return new SimpleAuthenticationInfo(userInfo,String.valueOf(token.getPassword()),getName());
    }
}
